import * as mqtt from 'mqtt'

export class MqttUtil {
  static instance = null;

  static getMqtt(url, option = {}) {
    if (!this.instance) {
      this.instance = new MqttUtil(url, option)
    }
    return this.instance
  }

  constructor(url, option = {}) {
    this.url = url || 'mqtt://127.0.0.1'
    this.client = mqtt.connect(this.url, option)
    this.connect()
  }

  connect(callback) {
    this.client.on('connect', function() {
      console.log('mqtt连接服务器成功')
      if (callback) callback()
    })
  }

  pubTopic(topic, message) {
    this.client.publish(topic, message)
  }

  setSubTopic(topic) {
    this.client.subscribe(topic)
  }

  subTopic(callback, that) {
    console.log("接受", that);
    this.client.on('message', function(topic, message) {
      // console.log(topic,message.toString());
      if (callback) {
        if (that) {
          callback.call(that, topic, message)
        } else {
          callback(topic, message)
        }
      }
    })
  }
}
